package handler

import (
	"encoding/json"
	"errors"
	"log"
	"net/http"

	"cloud-disk/core/internal/logic"
	"cloud-disk/core/internal/svc"
	"cloud-disk/core/internal/types"
	"github.com/zeromicro/go-zero/rest/httpx"
)

func MailCodeSendRegisterHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req types.MailCodeSendRequest
		decoder := json.NewDecoder(r.Body)
		if err := decoder.Decode(&req); err != nil {
			log.Printf("JSON解析失败：%", err)
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}
		log.Printf("解析后的请求：%+v", req)

		l := logic.NewMailCodeSendRegisterLogic(r.Context(), svcCtx)
		resp, err := l.MailCodeSendRegister(&req)
		if err != nil {
			// 根据错误类型返回适当的 HTTP 状态码
			if errors.Is(err, ErrInvalidRequest) {
				httpx.Error(w, NewHttpError(http.StatusBadRequest, err.Error()))
			} else {
				httpx.Error(w, err)
			}
			return
		}

		httpx.OkJson(w, resp)
	}
}

// 定义一个自定义错误类型
var ErrInvalidRequest = errors.New("invalid request")

// 定义一个 HTTP 错误结构
type HttpError struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
}

func NewHttpError(code int, msg string) *HttpError {
	return &HttpError{Code: code, Msg: msg}
}

func (e *HttpError) Error() string {
	return e.Msg
}
